package com.weiyirong99.crm.app.ui;


import static android.os.Build.VERSION_CODES.M;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.ActivityUtils;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.tencent.mmkv.MMKV;
import com.weiyirong99.crm.app.R;
import com.weiyirong99.crm.app.api.Url;
import com.weiyirong99.crm.app.base.BaseActivity;
import com.weiyirong99.crm.app.bean.ClientModel;
import com.weiyirong99.crm.app.server.MyReceiver;
import com.weiyirong99.crm.app.server.PhoneStateReceiver;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import co.lujun.androidtagview.TagContainerLayout;


/**
 * author  by  Canrom7 .
 * CreateDate 2021/8/30 11:46
 * Class ClientDetailActivity  客户详情页
 */
public class ClientDetailActivity extends BaseActivity implements OnClickListener {


    private ImageView ivBack;

    private TextView tvname;

    private TextView tvphone;

    private android.widget.RatingBar tvstar;

    private TextView tvfollow;

    private TextView tvgroup;

    private co.lujun.androidtagview.TagContainerLayout tvattinfo;

    private TextView tvother;
    private TextView tvgenjin;
    private TextView tv_call;
    private String istuisong;
    private int id;
    private int REQUESTCODE = 1;
    private String phone;

    @Override
    public int getLayout() {
        return R.layout.activity_client_detail;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityReceiver myBroadcast = new ActivityReceiver();
        //创建IntentFilter
        IntentFilter filter = new IntentFilter();
        filter.addAction("ClientDetailActivity");
        registerReceiver(myBroadcast, filter);
    }

    @Override
    public void initView() {
        ivBack = (ImageView) findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        tvname = (TextView) findViewById(R.id.tvname);
        tvphone = (TextView) findViewById(R.id.tvphone);
        tvstar = (RatingBar) findViewById(R.id.tvstar);
        tvfollow = (TextView) findViewById(R.id.tvfollow);
        tvgroup = (TextView) findViewById(R.id.tvgroup);
        tvattinfo = (TagContainerLayout) findViewById(R.id.tvattinfo);
        tvother = (TextView) findViewById(R.id.tvother);
        tvgenjin = (TextView) findViewById(R.id.tv_genjin);
        tv_call = (TextView) findViewById(R.id.tv_call);
        tvgenjin.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), AddCustsActivity.class);
                intent.putExtra("customer_id", customer_id);
                intent.putExtra("phone", tvphone.getText().toString());
                startActivity(intent);
            }
        });
        tv_call.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_CALL);
                Uri data = Uri.parse("tel:" + tvphone.getText().toString());
                intent.setData(data);
                startActivityForResult(intent, 1);

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("WG", "onActivityResult: 进来了 " + resultCode + " :" );
        if (requestCode == 1) {
            Intent intent2 = new Intent(ClientDetailActivity.this, AddCustsActivity.class);
            intent2.putExtra("customer_id", customer_id);
            intent2.putExtra("phone", tvphone.getText().toString());
            startActivity(intent2);
        }

//        finish();

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        istuisong = intent.getStringExtra("isTuiSong");
        customer_id = intent.getIntExtra("customer_id", 0);
        phone = intent.getStringExtra("phone");
        id = MMKV.defaultMMKV().decodeInt("companyId");
        Log.e("WG", "onNewIntent: 1111  " + phone);
        loadData(id, customer_id, 1);
    }

    private int company_id, customer_id;

    @Override
    public void initParms(Bundle parms) {

//        int customerid = MMKV.defaultMMKV().decodeInt("customerid");

//        PhoneStateReceiver.register(ClientDetailActivity.this,customer_id);
        istuisong = getIntent().getStringExtra("isTuiSong");
        customer_id = getIntent().getIntExtra("customer_id", 0);
        phone = getIntent().getStringExtra("phone");
        id = MMKV.defaultMMKV().decodeInt("companyId");
        Log.e("WG", "onResume: 1111  " + phone);
        loadData(id, customer_id, 1);
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    public void setBean(ClientModel model) {
        tvname.setText(model.getName());
        tvphone.setText(model.getMobile());
        tvstar.setNumStars(5);
        tvstar.setRating(model.getStar().floatValue());
        switch (model.getState()) {
            case "UNKNOWN": {
                tvfollow.setText("未知");
                break;
            }
            case "WAIT_FOLLOW_UP": {
                tvfollow.setText("待跟进");
                break;
            }
            case "UNQUALIFIED": {
                tvfollow.setText("资质不符合");
                break;
            }
            case "WAIT_SIGN": {
                tvfollow.setText("待签约");
                break;
            }
            case "SIGNED": {
                tvfollow.setText("已签约");
                break;
            }
            case "VISITED": {
                tvfollow.setText("已上门");
                break;
            }

            case "APPROVAL": {
                tvfollow.setText("审核中");
                break;
            }
            case "LOAN": {
                tvfollow.setText("已放款");
                break;
            }
            case "EXAMINING": {
                tvfollow.setText("在审件");
                break;
            }
            case "INVALID": {
                tvfollow.setText("捣乱申请");
                break;
            }
            case "BLACK_LIST": {
                tvfollow.setText("黑名单");
                break;
            }

        }
        switch (model.getGroup()) {
            case "NEW_CUSTOMER": {
                tvgroup.setText("新客户");
                break;
            }
            case "A": {
                tvgroup.setText("A");
                break;
            }
            case "B": {
                tvgroup.setText("B");
                break;
            }
            case "C": {
                tvgroup.setText("C");
                break;
            }
            case "D": {
                tvgroup.setText("D");
                break;
            }
            case "E": {
                tvgroup.setText("E");
                break;
            }
            case "NEW_ALLOT": {
                tvgroup.setText("新分派");
                break;
            }
            case "EXPAND": {
                tvgroup.setText("拓展");
                break;
            }
            case "MORTGAGE": {
                tvgroup.setText("抵押");
                break;
            }
            case "LOCKED": {
                tvgroup.setText("锁定");
                break;
            }
        }
        List<String> tags = new ArrayList<>();
        if (model.getHasHouse() != null && model.getHasHouse()) {
            tags.add("有房");
        }
        if (model.getHasCar() != null && model.getHasCar()) {
            tags.add("又车");
        }
        if (model.getHasCreditCard() != null && model.getHasCreditCard()) {
            tags.add("信用卡");
        }
        if (model.getHasProvidentFund() != null && model.getHasProvidentFund()) {
            tags.add("公积金");
        }
        if (model.getHasSocialSecurity() != null && model.getHasSocialSecurity()) {
            tags.add("社保");
        }
        if (model.getHasInsurance() != null && model.getHasInsurance()) {
            tags.add("寿险保单");
        }
        if (model.getHasBusinessLicense() != null && model.getHasBusinessLicense()) {
            tags.add("营业执照");
        }
        if (model.getHasWages() != null && model.getHasWages()) {
            tags.add("工资流水");
        }
        if (model.getIsNative() != null && model.getIsNative()) {
            tags.add("本地人");
        }
        tvattinfo.setTags(tags);
        tvother.setText(model.getRemark());

    }

    private void loadData(int company_id, int customer_id, int type) {
//        MaterialDialog build = new MaterialDialog.Builder(getActivity())
//                .content("正在加载...")
//                .canceledOnTouchOutside(false)
//                .progress(true, 100)
//                .build();
//        build.show();

        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("pool", "BIZ");
        JSONObject jsonObject = new JSONObject(dataMap);
        OkGo.<String>get(Url.BaseUrl + "/api/company/" + company_id + "/customers/" + customer_id)
                .tag(ClientDetailActivity.this)
                .headers("Authorization", MMKV.defaultMMKV().decodeString("token"))
//                .upJson(jsonObject)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
//                        build.dismiss();
                        Log.e("WG", "onSuccess:111 " + response.body());
                        if (response.code() == 200) {
                            ClientModel clientModel = new Gson().fromJson(response.body(), ClientModel.class);
                            String name = clientModel.getName();
                            Log.e("wg", "onSuccess:333 " + name);
                            setBean(clientModel);
                            if ((istuisong != null && istuisong.equals("1"))) {
                                istuisong = "2";
                                Intent intent = new Intent(Intent.ACTION_CALL);
                                Uri data = Uri.parse("tel:" + phone);
                                intent.setData(data);
                                startActivityForResult(intent, 1);
//                                call(intent, tvphone.getText().toString());
//                                Uri data = Uri.parse("tel:" + tvphone.getText().toString());
//                                intent.setData(data);
//                                startActivityForResult(intent, 1);
                            }
                        } else {
                            try {
                                JSONObject jsonObject = new JSONObject(response.body());
                                String message = jsonObject.getString("message");
//                            Log.e("wg", "onSuccess:222 " + message);
                                ts(message);
                            } catch (JSONException e) {
                                Log.e("WG", "onSuccess: " + e.toString());
                                e.printStackTrace();
                            }
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Log.e("WG", "onError: ");
//                        build.dismiss();
                        ts(response.message());
                    }
                });
    }


    @Override
    public BaseActivity getActivity() {
        return ClientDetailActivity.this;
    }


    @Override
    public void onClick(View view) {
        finish();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        PhoneStateReceiver.unregister(ClientDetailActivity.this);
    }

    private class ActivityReceiver extends BroadcastReceiver {


        @Override
        public void onReceive(Context context, Intent intent) {
            //获取来自receive中intent的update消息，代表播放状态
            Log.e("WG", "onReceive: 111111 ");
            istuisong = intent.getStringExtra("isTuiSong");
            customer_id = intent.getIntExtra("customer_id", 0);
            phone = intent.getStringExtra("phone");
            Log.e("WG", "onReceive: " + customer_id);
            loadData(id, customer_id, 0);
            intent = new Intent(Intent.ACTION_CALL);
            Uri data = Uri.parse("tel:" + phone);
            intent.setData(data);
            startActivityForResult(intent, 1);
//            checkPermission(intent, phone);

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull @NotNull String[] permissions, @NonNull @NotNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUESTCODE) {
            if (grantResults != null && grantResults.length > 0) {
                //判断用户是否授予了这个权限
                //因为目前只有打电话这一个权限结果所以使用grantResults[0]
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                } else {
                    Toast.makeText(this, "您拒绝了拨打电话的权限", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    private void checkPermission(Intent intent, String phone) {
        //1.判断当前手机系统是否大于或等于6.0
        //4.如果有打电话的授权，就直接拨打电话
        //1.判断当前手机系统是否大于或等于6.0
        if (Build.VERSION.SDK_INT >= M) {
            //2.如果大于6.0，则检查是否有打电话的权限授权
            int isPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE);//用于检测程序是否包含某项权限
            //下面的log如果程序第一次运行checkPermission一般是-1，需要下面的ActivityCompat.requestPermissions去动态
            //申请权限，当你动态申请过一次后下次就不是-1了，除非删掉程序。
            Log.d(TAG, "checkPermission: " + isPermission);
            if (isPermission == PackageManager.PERMISSION_GRANTED) {
                //4.如果有打电话的授权，就直接拨打电话
                call(intent, phone);
            } else {
                //3.如果没有打电话的授权，就要去申请打电话的权限
                //下面为申请权限的方法，下面的onRequestPermissionsResult方法用于验证此方法申请成功或失败（到时会弹出一个对话框给你选择允许拒绝）
                //也会导致回调onRequestPermissionsResult方法
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, REQUESTCODE);
            }
        } else {
            //5.如果当前版本小于6.0，直接拨打电话
            call(intent, phone);
        }
    }

    private void call(Intent intent, String phone) {
//        intent = new Intent(Intent.ACTION_CALL);

    }
}
